import java.util.Map;
import javax.persistence.*;
import org.apache.openjpa.persistence.*;

public class ConexionBBDD
{
    public EntityManagerFactory factory;
    private EntityManager em;
    public OpenJPAEntityManager kem;

    private Map getProperties()
    {
        Map properties = System.getProperties();

        properties.put("openjpa.ConnectionURL", "jdbc:postgresql://127.0.0.1:5432/prueba");
        properties.put("openjpa.ConnectionUserName", "postgres");
        properties.put("openjpa.ConnectionPassword", "postgres");
        properties.put("openjpa.ConnectionDriverName", "org.postgresql.Driver");
        properties.put("openjpa.ConnectionFactoryProperties","PrettyPrint=true, PrettyPrintLineLength=80");
        return properties;
    }

    public ConexionBBDD() throws Exception 
    {
        try {
            // System.out.println("Creamos la factoria de EntityManagers con el nombre que le hemos dado a en la declaracion del xml persistence-unit name");
            factory = Persistence.createEntityManagerFactory("reversemappingtool", getProperties());
            
            // System.out.println("createEntityManager: factory: " + factory);
            em = factory.createEntityManager();

            // System.out.println("EntityManager: em: " + em);
            kem = OpenJPAPersistence.cast(em);
        } catch (Exception e) {
            System.err.println("Error al crear la sesion OpenJPA de base de datos." + e.getMessage());
            throw new Exception(e.getMessage());
        }
    }
    
    public void cerrarConexion()
    {
        if (kem != null) {
            kem.close();
        }
        if (factory != null) {
            factory.close();
        }
    }
}
